using Grpc.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading.Tasks;
using Upload;

namespace Server;

public class UploaderService : Uploader.UploaderBase
{
    private readonly ILogger _logger;
    private readonly IConfiguration _config;

    public UploaderService(ILoggerFactory loggerFactory, IConfiguration config)
    {
        _logger = loggerFactory.CreateLogger<UploaderService>();
        _config = config;
    }

    public override async Task<UploadFileResponse> UploadFile(IAsyncStreamReader<UploadFileRequest> requestStream, ServerCallContext context)
    {
        var uploadId = Path.GetRandomFileName();
        var uploadPath = Path.Combine(_config["StoredFilesPath"]!, uploadId);
        Directory.CreateDirectory(uploadPath);

        await using var writeStream = File.Create(Path.Combine(uploadPath, "data.bin"));

        await foreach (var message in requestStream.ReadAllAsync())
        {
            if (message.Metadata != null)
            {
                await File.WriteAllTextAsync(Path.Combine(uploadPath, "metadata.json"), message.Metadata.ToString());
            }
            if (message.Data != null)
            {
                await writeStream.WriteAsync(message.Data.Memory);
            }
        }

        return new UploadFileResponse { Id = uploadId };
    }
}
